package com.xiumu.service.blog.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiumu.common.core.exception.blog.BlogException;
import com.xiumu.common.core.page.PageQuery;
import com.xiumu.common.core.utils.AssertUtil;
import com.xiumu.dao.blog.BlogTagDao;
import com.xiumu.pojo.blog.entity.BlogTag;
import com.xiumu.pojo.blog.query.BlogTagQuery;
import com.xiumu.service.blog.BlogTagService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 文章标签 Service 接口实现
 *
 * @author XiuMu
 * @Date 2023-01-30 14:21:26
 */
@Service
public class BlogTagServiceImpl extends ServiceImpl<BlogTagDao, BlogTag> implements BlogTagService {
    @Override
    public Page<BlogTag> listPage(PageQuery<BlogTagQuery, BlogTag> pageQuery) {
        return this.baseMapper.selectPage(pageQuery.toPage(), pageQuery.getCondition());
    }

    @Override
    public List<BlogTag> listByBlogTag(BlogTagQuery blogTag) {
        return this.baseMapper.selectByBlogTag(blogTag);
    }

    @Override
    public BlogTag getByTagName(String tagName) {
        return getOne(new LambdaQueryWrapper<BlogTag>().eq(BlogTag::getTagName, tagName));
    }

    @Override
    @Transactional
    public boolean create(String tagName) {
        AssertUtil.isTrue(StrUtil.isNotBlank(tagName), BlogException.EMPTY_TAG_NAME);
        BlogTag tag = getByTagName(tagName);
        if (tag == null) {
            // 标签不存在才创建
            return this.save(new BlogTag(tagName));
        }
        return true;
    }

    @Override
    public Long getIdOrSaveByTagName(String tagName) {
        BlogTag tag = getByTagName(tagName);
        if (tag == null){
            tag = new BlogTag(tagName);
            save(tag);
        }
        return tag.getId();
    }
}




